package cn.com.dhcc.ddi.datasource.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.base.ResultVo;
import cn.com.dhcc.app.core.dao.SimpleDaoForOracle;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.tag.staticcode.StaticCode.DB_TYPE;
import cn.com.dhcc.ddi.datasource.dao.DataSourceDao;
import cn.com.dhcc.ddi.datasource.dao.DataSourceMysqlDao;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.datasource.vo.TableColVo;
import cn.com.dhcc.ddi.datasource.vo.TableInfoVo;
/**
 * 数据源管理服务
 * @author qiao
 * 2017-3-8 下午2:42:53
 */
@Service
public class DataSourceDBService extends BaseService {
	@Autowired
	DataSourceMysqlDao dataSourceMysqlDao;
	@Autowired
	DataSourceMysqlService dataSourceMysqlService;
	@Autowired
	DataSourceDao dataSourceDao;
	private static Logger logger = Log.getLogger(LOGTYPE.DDI);
	
	/**
	 * 
	    * @Title: dsStatusOk
	    * @Description: 验证数据库连接状态
	    * @param @param dataSource
	    * @param @return
	    * @param @throws NiceException    参数
	    * @return boolean    返回类型
	    * @throws
	 */
	public boolean dsStatusOk(DataSourceVo dataSource) {
		
		try {
			final SimpleDaoForOracle dao = dataSourceDao.initDao(dataSource);
			if (dao == null) return false;
			DB_TYPE dbType = DB_TYPE.find(dataSource.getDataSourceConfVo().getDbType());
			String dbconf = dataSource.getConf();
			if (StrUtil.isNotBank(dbconf)) {//去掉敏感数据比如：密码
				dbconf = dbconf.replaceFirst(",\"(?=password).+", "");
			}
			ResultVo resultVo = dao.isValidate(dbType.getValidateUrl());
			if (!resultVo.isResult()) {
				logger.error(resultVo.getMsg());
			}
			return resultVo.isResult();
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 
	 * @Title: insert
	 * @Description: 数据源信息入库
	 * @param @param vo
	 * @param @param tbInfoList
	 * @param @param tbColInfoList
	 * @param @throws ServiceException 参数
	 * @return void 返回类型
	 * @throws
	 */
	public void insert(final DataSourceVo vo, String tbInfoList, String tbColInfoList) throws ServiceException {
		try {
			List<Object[]> tableInfoList = getTableInfoArray(tbInfoList);
			List<Object[]> tableColInfoList = getTableColArray(tbColInfoList);
			dataSourceMysqlDao.insert(vo, tableInfoList, tableColInfoList);
		} catch (DaoException e) {
			throw new ServiceException("数据源信息入库失败", e);
		}
	}

	/**
	 * 
	 * @Title: update
	 * @Description: 数据源信息修改
	 * @param @param vo
	 * @param @param tbInfoList
	 * @param @param tbColInfoList
	 * @param @throws ServiceException 参数
	 * @return void 返回类型
	 * @throws
	 */
	public void update(final DataSourceVo vo, String tbInfoList, String tbColInfoList) throws ServiceException {
		try {
			List<TableInfoVo> tableInfoList = getTableInfoUpdate(tbInfoList);
			List<TableColVo> tableColInfoList = getTableColUpdate(tbColInfoList);
			dataSourceMysqlService.update(vo, tableInfoList, tableColInfoList);
		} catch (DaoException e) {
			throw new ServiceException("数据源信息修改失败", e);
		}
	}

	/**
	 * 
	 * @Title: getTableInfoArray
	 * @Description: 获取表信息新增时的参数List<Object[]>
	 * @param @param tbInfoList
	 * @param @return 参数
	 * @return List<Object[]> 返回类型
	 * @throws
	 */
	public List<Object[]> getTableInfoArray(String tbInfoList) {
		List<Object[]> list = new ArrayList<Object[]>();
		JSONArray tbInfoArray = new JSONArray(tbInfoList);
		for (int i=0;i<tbInfoArray.length();i++) {
			String tbInfo = (String)tbInfoArray.get(i);
			Map<String,String> map = new HashMap<String, String>();
			map = JsonUtil.toMap(tbInfo);
			Object[] obj = new Object[7];
			obj[0] = StrUtil.isBlank((String)map.get("id")) ? UUIDGenerator.getUUID() : (String)map.get("id");
			obj[1] = (String)map.get("dsId");
			obj[2] = (String)map.get("tableName");
			obj[3] = (String)map.get("schema");
			obj[4] = (String)map.get("tableComment");
			obj[5] = null;//tableOrder
			obj[6] = new Date();
			list.add(obj);
		}
		return list;
	}

	/**
	 * 
	 * @Title: getTableInfoUpdate
	 * @Description: 获取表信息修改时的参数List<Object[]>
	 * @param @param tbInfoList
	 * @param @return 参数
	 * @return List<Object[]> 返回类型
	 * @throws
	 */
	public List<TableInfoVo> getTableInfoUpdate(String tbInfoList) {
		List<TableInfoVo> list = new ArrayList<TableInfoVo>();
		JSONArray tbInfoArray = new JSONArray(tbInfoList);
		for (int i=0;i<tbInfoArray.length();i++) {
			String tbInfo = (String)tbInfoArray.get(i);
			Map<String,String> map = new HashMap<String, String>();
			map =JsonUtil.toMap(tbInfo);
			TableInfoVo vo = new TableInfoVo();
			vo.setId((String)map.get("id"));
			vo.setDsId((String)map.get("dsId"));
			vo.setTableName((String)map.get("tableName"));
			vo.setSchema((String)map.get("schema"));
			vo.setTableComment((String)map.get("tableComment"));
			vo.setMtime(new Date());
			list.add(vo);
		}
		return list;
	}

	/**
	 * 
	 * @Title: getTableColArray
	 * @Description: 获取表字段信息新增时的参数List<Object[]>
	 * @param @param tbColInfoList
	 * @param @return 参数
	 * @return List<Object[]> 返回类型
	 * @throws
	 */
	public List<Object[]> getTableColArray(String tbColInfoList) {
		List<Object[]> list = new ArrayList<Object[]>();
		JSONArray tbColInfoArray = new JSONArray(tbColInfoList);
		for (int i = 0; i < tbColInfoArray.length(); i++) {
			Object[] obj = new Object[11];
			String tbColInfo = (String)tbColInfoArray.get(i);
			tbColInfo = relaceStr(tbColInfo);
			Map<String,String> map = JsonUtil.toMap(tbColInfo);
			obj[0] = StrUtil.isBlank((String)map.get("id")) ? UUIDGenerator.getUUID() : (String)map.get("id");
			obj[1] = (String)map.get("tableId");
			obj[2] = (String)map.get("colName");
			obj[3] = (String)map.get("colType");
			obj[4] = (String)map.get("colComment");
			obj[5] = (String)map.get("isPk");
			obj[6] = (String)map.get("isIc");
			obj[7] = (String)map.get("fkTableName");
			obj[8] = (String)map.get("fkTablecolName");
			obj[9] = new Date();
			obj[10] = (String)map.get("colDefault");
			list.add(obj);
		}
		return list;
	}

	/**
	 * 
	 * @Title: getTableColUpdate
	 * @Description: 获取表字段信息修改时的参数List<Object[]>
	 * @param @param tbColInfoList
	 * @param @return 参数
	 * @return List<Object[]> 返回类型
	 * @throws
	 */
	public List<TableColVo> getTableColUpdate(String tbColInfoList) {
		List<TableColVo> list = new ArrayList<TableColVo>();
		JSONArray tbColInfoArray = new JSONArray(tbColInfoList);
		for (int i = 0; i < tbColInfoArray.length(); i++) {
			String tbColInfo = (String)tbColInfoArray.get(i);
			tbColInfo = relaceStr(tbColInfo);
			Map<String,String> map = JsonUtil.toMap(tbColInfo);
			TableColVo vo = new TableColVo();
			vo.setId((String)map.get("id"));
			vo.setDsId((String)map.get("dsId"));
			vo.setTableId((String)map.get("tableId"));
			vo.setTableName((String)map.get("tableName"));
			vo.setColName((String)map.get("colName"));
			vo.setColType((String)map.get("colType"));
			vo.setColDefault((String)map.get("colDefault"));
			vo.setColComment((String)map.get("colComment"));
			vo.setIsPk((String)map.get("isPk"));
			vo.setIsIc((String)map.get("isIc"));
			vo.setFkTableName((String)map.get("fkTableName"));
			vo.setFkTablecolName((String)map.get("fkTablecolName"));
			vo.setMtime(new Date());
			list.add(vo);
		}
		return list;
	}
	
	/**
	 * 
	    * @Title: relaceStr
	    * @Description: 去除字符串中的空格、换行符、制表符、回车
	    * @param @param str
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	public String relaceStr(String str){
		String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
	}
	
	
}
